import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Space, Spin, message, Table, DatePicker, Progress, Modal, Input } from 'antd';
import { history } from 'umi';
import PPContainer from '@/components/PPContainer';
import PPCard from '@/components/PPCard';
import PPBlock from '@/components/PPBlock';
import PPTable from '@/components/PPTable';
import PPButton from '@/components/PPButton';
import PPSampleButton from '@/components/PPSampleButton';
import PPSplitDatasetModal from '@/components/PPProjectOverview/PPSplitDatasetModal';
import PPExportModal from '@/components/PPProjectOverview/PPExportModal';
import PPUpdataModal from '@/components/PPProjectOverview/PPUpdataModal';
import PPOverlapCol from '@/components/PPOverlapCol';
import { toDict, ProjectUtils, getVersion, snake2camel, TaskUtils, camel2snake } from '@/services/utils';
import { IntlInitJsx } from '@/components/PPIntl';
import { createInfo } from '@/services/utils';
import type { ColumnsType } from 'antd/es/table';
import type { Project } from '@/services/web/models';
import * as runtime from '../../services/web/runtime';
import { ProjectApi, Configuration } from '@/services/web';
import { parse } from '@babel/core';
import { set } from 'lodash';

const baseUrl = localStorage.getItem('basePath');
const config = new Configuration(baseUrl ? { basePath: baseUrl } : undefined);
const projectApi = new ProjectApi(config);

const Projects: React.FC = (props) => {
  const intl = IntlInitJsx('pages.welcome');

  const projects = ProjectUtils(useState);
  const task = TaskUtils(useState);

  useEffect(() => {
    getVersion().then((version) => {
      if (version != false) {
        projects.getAll(1, 10);
      }
    });
  }, []);

  const [isTimePickerVisible, setIsTimePickerVisible] = useState(false);
  const [isUserTimePickerVisible, setIsUserTimePickerVisible] = useState(false);
  const [isDownloadTimePickerVisible, setIsDownloadTimePickerVisible] = useState(false);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [startTime, setStartTime] = useState<string>('');
  const [endTime, setEndTime] = useState<string>('');
  const [userStartTime, setUserStartTime] = useState<string>('');
  const [userEndTime, setUserEndTime] = useState<string>('');
  const [downloadTime, setDownloadTime] = useState<string>('');
  const [annResult, setAnnResult] = useState<any>(null);
  const [isAnnModalVisible, setIsAnnModalVisible] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState(0);
  const [isDownloadCancelled, setIsDownloadCancelled] = useState(false);
  const [isDownloadModalVisible, setIsDownloadModalVisible] = useState(false); // 新增状态
  // const [isDownloadMinimized, setIsDownloadMinimized] = useState(false); // 新增状态
  const [isDownloadMinimized, setIsDownloadMinimized] = useState<boolean>(() => {
    const storedValue = localStorage.getItem('isDownloadMinimized');
    return storedValue ? JSON.parse(storedValue) : false;
  });

  // 更新 localStorage 当 isDownloadMinimized 改变时
  useEffect(() => {
    localStorage.setItem('isDownloadMinimized', JSON.stringify(isDownloadMinimized));
  }, [isDownloadMinimized]);

  // 获取最新的下载进度
  const fetchLatestDownloadProgress = async () => {
    try {
      const progressRes = await projectApi.download_progress();
      if (progressRes && progressRes.result && progressRes.result.progress) {
        const progress = parseInt(progressRes.result.progress);
        setDownloadProgress(progress);
        localStorage.setItem('downloadProgress', progress.toString());
        if (progress === -1) {
          setIsDownloading(false);
          setIsDownloadModalVisible(false); //隐藏进度条模态框
          localStorage.setItem('isDownloading', JSON.stringify(false));
          localStorage.setItem('isDownloadModalVisible', JSON.stringify(false));
          message.error('获取下载进度失败');
        } else {
          setIsDownloading(progress < 100);
          localStorage.setItem('isDownloading', JSON.stringify(progress < 100));
        }
      }
    } catch (error) {
      message.error('获取下载进度失败');
    }
  };



  // 定期请求最新的下载进度
  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (isDownloading) {
      intervalId = setInterval(fetchLatestDownloadProgress, 2000); // 每2秒请求一次
    }

    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [isDownloading]);


  // 在组件重新加载时获取最新的下载进度
  useEffect(() => {
    if (isDownloadMinimized) {
      fetchLatestDownloadProgress();
    }
  }, [isDownloadMinimized]);

  // 初始化时恢复下载状态
  useEffect(() => {
    const storedIsDownloading = localStorage.getItem('isDownloading');
    const storedDownloadProgress = localStorage.getItem('downloadProgress');
    const storedIsDownloadCancelled = localStorage.getItem('isDownloadCancelled');
    const storedIsDownloadModalVisible = localStorage.getItem('isDownloadModalVisible');

    if (storedIsDownloading) {
      setIsDownloading(JSON.parse(storedIsDownloading));
    }
    if (storedDownloadProgress) {
      setDownloadProgress(parseInt(storedDownloadProgress));
    }
    if (storedIsDownloadCancelled) {
      setIsDownloadCancelled(JSON.parse(storedIsDownloadCancelled));
    }
    if (storedIsDownloadModalVisible) {
      setIsDownloadModalVisible(JSON.parse(storedIsDownloadModalVisible));
    }

    if (isDownloading) {
      fetchLatestDownloadProgress();
    }
  }, []);


  const handleSelectTime = (project: Project) => {
    setSelectedProject(project);
    setIsTimePickerVisible(true);
  };

  const handleUserSelectTime = (project: Project) => {
    setSelectedProject(project);
    setIsUserTimePickerVisible(true);
  };

  const handleTimePickerOk = async () => {
    if (selectedProject && startTime && endTime) {
      try {
        const res = await projectApi.select_ann(selectedProject.project_id, startTime, endTime);
        if (res && res.result) {
          setAnnResult(res.result);
          setIsAnnModalVisible(true);
        }
      } catch (error) {
        message.error('查询失败');
      }
    }
    setIsTimePickerVisible(false);
  };

  const handleUserTimePickerOk = async () => {
    if (selectedProject && userStartTime && userEndTime) {
      try {
        const username = localStorage.getItem('username');
        const res = await projectApi.select_ann(selectedProject.project_id, userStartTime, userEndTime, username);
        if (res && res.result) {
          setAnnResult(res.result);
          setIsAnnModalVisible(true);
        }
      } catch (error) {
        message.error('查询失败');
      }
    }
    setIsUserTimePickerVisible(false);
  };

  const handleTimePickerCancel = () => {
    setIsTimePickerVisible(false);
  };

  const handleUserTimePickerCancel = () => {
    setIsUserTimePickerVisible(false);
  };

  const handleDownloadTimePickerOk = async () => {
    if (downloadTime) {
      try {
        const res = await projectApi.download_image(downloadTime);
        if (res && res.status === 200) {
          message.success(res.message);
          if (!isDownloading || isDownloadCancelled) {
            setIsDownloading(true);
            setDownloadProgress(0);
            setIsDownloadCancelled(false);
            setIsDownloadModalVisible(true); // 显示进度条模态框
            localStorage.setItem('isDownloading', JSON.stringify(true));
            localStorage.setItem('downloadProgress', '0');
            localStorage.setItem('isDownloadCancelled', JSON.stringify(false));
            localStorage.setItem('isDownloadModalVisible', JSON.stringify(true));
            const intervalId = setInterval(async () => {
              try {
                const progressRes = await projectApi.download_progress();
                if (progressRes && progressRes.result && progressRes.result.progress) {
                  const progress_2 = parseInt(progressRes.result.progress);
                  setDownloadProgress(progress_2);
                  localStorage.setItem('downloadProgress', progress_2.toString());
                  if (progress_2 === -1) {
                    // 进度值为 -1，停止调用接口并提示下载失败
                    clearInterval(intervalId);
                    setIsDownloading(false);
                    setIsDownloadModalVisible(false); // 隐藏进度条模态框
                    localStorage.setItem('isDownloading', JSON.stringify(false));
                    localStorage.setItem('isDownloadModalVisible', JSON.stringify(false));
                    message.error('下载失败');
                  } else if (progress_2 >= 100) {
                    clearInterval(intervalId);
                    setIsDownloading(false);
                    setIsDownloadModalVisible(false); // 隐藏进度条模态框
                    localStorage.setItem('isDownloading', JSON.stringify(false));
                    localStorage.setItem('isDownloadModalVisible', JSON.stringify(false));
                    window.open(res.result);
                    message.success(res.message);
                  }
                }
              } catch (error) {
                message.error(res.message || '下载失败');
                clearInterval(intervalId);
                setIsDownloading(false);
                setIsDownloadModalVisible(false); // 隐藏进度条模态框
                localStorage.setItem('isDownloading', JSON.stringify(false));
                localStorage.setItem('isDownloadModalVisible', JSON.stringify(false));
              }
            }, 1000);
          } else {
            // 如果已经在下载，直接显示进度条模态框
            setIsDownloadModalVisible(true);
            localStorage.setItem('isDownloadModalVisible', JSON.stringify(true));
          }
        } else {
          message.error(res.message);
        }
      } catch (error) {
        message.error(res.message || '下载失败');
      }
    } else {
      message.error('请选择日期');
    }
    setIsDownloadTimePickerVisible(false);
  };

  const handleDownloadTimePickerCancel = () => {
    setIsDownloadTimePickerVisible(false);
    // 重置下载状态
    setDownloadProgress(0);
    setIsDownloadModalVisible(false);
  };

  const fetchProjects = (page: number, pageSize: number) => {
    projects.getAll(page, pageSize);
  };

  const role = localStorage.getItem('Role');
  console.log("role:", role);

  const columns: ColumnsType<Project> = [
    {
      title: 'ID',
      dataIndex: 'project_id',
      key: 'project_id',
      width: '4.5rem',
      align: 'center',
      render: (text: string) => <>{text}</>,
      sorter: (a, b) => a.project_id - b.project_id,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'project_id',
      width: '30rem',
    },
    {
      title: 'Project Category',
      key: 'project_id',
      width: '20rem',
      render: (project) => {
        const categoryName = snake2camel(project.task_category.name);
        return intl(categoryName, 'global');
      },
    },
    {
      title: 'Created',
      dataIndex: 'created',
      key: 'created',
      width: '20rem',
    },
    {
      title: 'State',
      key: 'project_id',
      width: '30rem',
      render: (project) => {
        const categoryName = snake2camel(project.state);
        return categoryName;
      },
    },
    {
      title: 'Actions',
      key: 'project_id',
      align: 'center',
      render: (text, project) => {
        if (role === '1') {
          return <Space size="middle">
            <PPButton
              width="4.375rem"
              height="1.875rem"
              color={'rgba(241,162,0,1)'}
              onClick={() => {
                history.push(`/project_overview?projectId=${project.project_id}`);
              }}
            >
              {intl('overview')}
            </PPButton>
            <PPButton
              width="8.375rem"
              height="1.875rem"
              color={'rgba(255,97,3,1)'}
              onClick={() => handleSelectTime(project)}
            >
              {intl('selectDate')}
            </PPButton>
            <PPButton
              width="4.375rem"
              height="1.875rem"
              color={'rgba(255,97,3,1)'}
              onClick={() => {
                history.push(
                  `/project_detail?taskCategory=${snake2camel(
                    project.task_category.name,
                  )}&projectId=${project.project_id}`,
                );
              }}
            >
              {intl('projectEdit')}
            </PPButton>
            <PPUpdataModal
              project={project}
            />
            <PPSplitDatasetModal
              project={projects}
              project_id={project.project_id}
              onFinish={() => task.getAll(project.project_id)}
            />
            <PPExportModal
              project={project}
            />
            <PPButton
              width="4.375rem"
              height="1.875rem"
              color={'rgba(207,63,0,1)'}
              onClick={() => {
                props.setDeleting(true);
                projects.remove(project.project_id).then(() => props.setDeleting(false));
              }}
            >
              {intl('remove')}
            </PPButton>
          </Space>;
        } else {
          if (project && project.state === '未完成') {
            return <Space size="middle">
              <Button
                type="primary"
                onClick={() => {
                  localStorage.removeItem('currDataId');
                  localStorage.removeItem('projectId');
                  history.push(
                    `/${camel2snake(project.task_category.name)}?projectId=${project.project_id}`,
                  );
                }}
              >
                {intl('label')}
              </Button>

              <PPButton
                width="8.375rem"
                height="1.875rem"
                color={'rgba(255,97,3,1)'}
                onClick={() => handleUserSelectTime(project)}
              >
                {intl('selectUserDate')}
              </PPButton>
            </Space>;
          }
        }
      },
    },
  ];

  const project_data = new runtime.JSONApiResponse(projects.all).raw;
  if (project_data !== undefined) {
    if (project_data.count === 0) {
      return '';
    } else {
      return (
        <Row style={{ marginTop: 20 }}>
          <Col span={24}>
            <Space style={{ marginBottom: 20 }}>
              {role === '1' && (
                <PPButton
                  width="8.375rem"
                  height="1.875rem"
                  color={'rgba(255,97,3,1)'}
                  onClick={() => {
                    if (isDownloading && !isDownloadCancelled) {
                      setIsDownloadModalVisible(true); // 直接显示进度条模态框
                    } else {
                      setIsDownloadTimePickerVisible(true);
                    }
                  }}
                >
                  {intl('downloadImage')}
                </PPButton>
              )}
            </Space>
            <PPBlock title={intl('myProjects')}>
              <PPTable columns={columns} dataSource={toDict(project_data.data_list)} showHeader={false} totalNum={project_data.count} onPageChange={fetchProjects} />
            </PPBlock>
          </Col>
          <Modal
            title={intl('selectDate')}
            visible={isTimePickerVisible}
            onOk={handleTimePickerOk}
            onCancel={handleTimePickerCancel}
            okText={intl('confirm')}
            cancelText={intl('cancel')}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <DatePicker.RangePicker
                showTime
                format="YYYY-MM-DD HH:mm"
                onChange={(dates) => {
                  if (dates) {
                    setStartTime(dates[0].format('YYYY-MM-DD HH:mm'));
                    setEndTime(dates[1].format('YYYY-MM-DD HH:mm'));
                  }
                }}
              />
            </Space>
          </Modal>

          <Modal
            title="标注结果"
            visible={isAnnModalVisible}
            onOk={() => setIsAnnModalVisible(false)}
            onCancel={() => setIsAnnModalVisible(false)}
            okText={intl('confirm')}
            cancelText={intl('cancel')}
          >
            {annResult && (
              <Table
                dataSource={annResult}
                columns={[
                  {
                    title: intl('username'),
                    dataIndex: 'username',
                    key: 'username',
                  },
                  {
                    title: intl('annotatedDataCount'),
                    dataIndex: 'annotated_data_count',
                    key: 'annotated_data_count',
                  },
                ]}
                pagination={false}
                rowKey="username"
              />
            )}
          </Modal>

          <Modal
            title={intl('selectDate')}
            visible={isUserTimePickerVisible}
            onOk={handleUserTimePickerOk}
            onCancel={handleUserTimePickerCancel}
            okText={intl('confirm')}
            cancelText={intl('cancel')}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <DatePicker.RangePicker
                showTime
                format="YYYY-MM-DD HH:mm"
                onChange={(dates) => {
                  if (dates) {
                    setUserStartTime(dates[0].format('YYYY-MM-DD HH:mm'));
                    setUserEndTime(dates[1].format('YYYY-MM-DD HH:mm'));
                  }
                }}
              />
            </Space>
          </Modal>

          <Modal
            title="选择日期"
            visible={isDownloadTimePickerVisible}
            onOk={handleDownloadTimePickerOk}
            onCancel={handleDownloadTimePickerCancel}
            okText={intl('confirm')}
            cancelText={intl('cancel')}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <DatePicker
                format="YYYY-MM-DD"
                onChange={(date) => {
                  if (date) {
                    setDownloadTime(date.format('YYYY-MM-DD'));
                  }
                }}
              />
            </Space>
          </Modal>

          <Modal
            title="下载进度"
            visible={isDownloadModalVisible}
            footer={null}
            closeIcon={<Button onClick={() => setIsDownloadMinimized(true)}>X</Button>}
            onCancel={() => setIsDownloadModalVisible(false)}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Progress percent={downloadProgress} status={isDownloading ? 'active' : 'success'} />
            </div>
          </Modal>

          {/* {isDownloadMinimized && (
            <Button
              style={{ position: 'fixed', bottom: 20, right: 20 }}
              onClick={() => {
                setIsDownloadModalVisible(true);
                fetchLatestDownloadProgress(); // 点击按钮时获取最新的下载进度
              }}
            >
              恢复下载进度
            </Button>
          )} */}
        </Row>
      );
    }
  }
};

const Welcome: React.FC = () => {
  const intl = IntlInitJsx('pages.welcome');

  const [deleting, setDeleting] = useState<boolean>(false);

  function createButtons() {
    const creators = [];
    for (const [taskCategory, info] of Object.entries(createInfo)) {
      creators.push(
        <PPOverlapCol span={4}>
          <PPCard
            imgSrc={info.avatar}
            href={'/project_detail?taskCategory=' + taskCategory}
            onClick={
              taskCategory != 'keypointDetection'
                ? undefined
                : () => {
                  message.info(intl('underDevelopment', 'global'));
                }
            }
          >
            {intl(taskCategory, 'global')}
          </PPCard>
        </PPOverlapCol>,
      );
    }
    return creators;
  }

  return (
    <PPContainer>
      <Row gutter={[20, 20]} style={{ marginTop: 20 }}>
        {localStorage.getItem('Role') === '1' && (
          <Col span={24}>
            <PPBlock title={intl('createProject')} style={{ height: 430 }}>
              <Row style={{ marginLeft: 300 }}>{createButtons()}</Row>
            </PPBlock>
          </Col>
        )}
      </Row>
      <Spin tip="Deleting" spinning={deleting}>
        {Projects({ setDeleting: setDeleting })}
      </Spin>
    </PPContainer>
  );
};

export default Welcome;
